package com.caigou.service.impl;

import com.caigou.bean.exam.entity.UserInfo;
import com.caigou.component.OSSComponent;
import com.caigou.enums.ResponseEnum;
import com.caigou.mapper.exam.UserInfoMapper;
import com.caigou.service.IFileUploadService;
import com.caigou.util.FileUtil;
import com.caigou.util.Result;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

@Service
@Slf4j
public class FileUploadServiceImpl implements IFileUploadService {
    @Resource
    private OSSComponent ossComponent;
    @Resource
    private UserInfoMapper userInfoMapper;

    /**
     * @param file
     * @return
     */
    public Result<String> uploadPicture(MultipartFile file, String userid) {
        log.info("开始上传头像");
        try {
            String fileName = file.getOriginalFilename();
            InputStream originInputStream = file.getInputStream();
            if (StringUtils.isEmpty(fileName)) {
                return Result.error(ResponseEnum.NOT_FIND_PICTURE_NAME);
            }
            String[] split = fileName.split("\\.");

            int length = split.length;
            log.info("输出:"+Arrays.toString(split));
            log.info("图片名称切割后长度"+length);
            String uuid =  UUID.randomUUID().toString().trim().replaceAll("-", "");
            String fileUrl = ossComponent.uploadToOSS(originInputStream, fileName, uuid, "headPortrait");
            UserInfo userInfo = userInfoMapper.findUserInfoByUserId(userid);
            if (userInfo == null) {
                return Result.error(ResponseEnum.UNKNOWN_USER);
            }
            log.info("用户id={}上传图片成功,图片路径={}",userInfo.getUserid(),fileUrl);
            return Result.success(fileUrl);

        } catch (IOException ioe) {
            log.error(ioe.getMessage(), ioe);
            throw new RuntimeException(ioe);
        }

    }

}
